package com.mystudio.android.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mystudio.android.calendar.adaptor.DaySummaryAdapter;
import com.mystudio.android.calendar.constants.Constants;
import com.mystudio.android.calendar.model.Instance;
import com.mystudio.android.calendar.util.LunarCalendar;
import com.mystudio.android.calendar.view.MonthListView;
import com.mystudio.android.calendar.view.OnDaySelectedListener;
import com.mystudio.android.calendar.view.OnMonthChangeListener;
import com.mystudio.android.util.Logger;

public class MonthActivity extends Activity {
    /** Called when the activity is first created. */
	private static final Logger logger = new Logger(Constants.LOG_TAG, MonthActivity.class);
	//private static final String[] COUNTRIES = new String[] {    "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",    "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",    "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",    "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",    "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",    "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",    "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",    "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",    "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",    "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",    "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",    "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",    "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",    "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",    "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",    "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",    "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",    "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",    "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",    "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",    "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",    "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",    "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",    "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",    "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",    "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",    "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",    "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",    "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",    "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",    "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",    "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",    "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",    "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",    "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",    "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",    "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",    "Ukraine", "United Arab Emirates", "United Kingdom",    "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",    "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",    "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"};
	
	private TextView monthTitleView;
	private Time tempTime = new Time();
	private DaySummaryAdapter mDaySummaryAdapter;
	private ListView mDaySummaryList;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

        //setContentView(new MyMonthView(this), new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        setContentView(R.layout.mymonth);

        // Calculate the left/right margin due to screen size division remains
        Display display = getWindowManager().getDefaultDisplay();
        int cellWidth = (display.getWidth() - 6) / 7;
        int actualTotalWidth = (cellWidth * 7) + 6;
        int leftMargin = (display.getWidth() - actualTotalWidth) / 2;
        int rightMargin = display.getWidth() - actualTotalWidth - leftMargin;
        
        LinearLayout weekDays = (LinearLayout)findViewById(R.id.WeekDays);
        //LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
        //	lp.setMargins(leftMargin, 1, rightMargin, 1); 
        //weekDays.setLayoutParams(lp);
        weekDays.setPadding(leftMargin, 0, rightMargin, 0);

        /*
        LinearLayout monthFrame = (LinearLayout)findViewById(R.id.MonthFrame);
        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        	lp.setMargins(leftMargin, 0, rightMargin, 0); 
        monthFrame.addView(new MyMonthView(this), lp);
        */

        LinearLayout monthFrame = (LinearLayout)findViewById(R.id.MonthFrame);
        //monthFrame.addView(new MonthScrollView(this), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));

        // Initialize the day summary list
        List<Instance> instances = new ArrayList<Instance>();
        Instance instance = new Instance();
        instance.title = "sdlfjdskfad";
        instances.add(instance);
        instances.add(instance);
        mDaySummaryAdapter = new DaySummaryAdapter(this, R.layout.day_summary_row, instances);
		mDaySummaryList = (ListView)findViewById(R.id.daySummaryList);
		mDaySummaryList.setAdapter(mDaySummaryAdapter);
        
        // Initialize the month list view
        monthTitleView = (TextView)findViewById(R.id.MonthTitle);
        MonthListView monthListView = (MonthListView)((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.month_list, monthFrame, false);
        	monthListView.setParentActivity(this);
	        monthListView.setOnMonthChangeListener(new OnMonthChangeListener() {
	    		@Override
	    		public void onCurrentMonthChanged(int year, int month) {
	    			Calendar date = Calendar.getInstance();
	    			date.set(Calendar.MONTH, month);
	    			monthTitleView.setText(String.format(getResources().getString(R.string.month_desc), String.valueOf(year), DateFormat.format("MMMM", date)));
	    		}
	    	});
	        monthListView.setOnDaySelectedListener(new OnDaySelectedListener() {
	        	@Override
	        	public void onDaySelected(int julianDay, List<Instance> instances) {
	        		// Set today relative desc text
	        		int todayJulianDay = Time.getJulianDay(System.currentTimeMillis(), tempTime.gmtoff);
	        		String todayRelativeDesc;
	        		if (julianDay == todayJulianDay) {
	        			todayRelativeDesc = (String)getResources().getText(R.string.today);
	        		} else if (julianDay+1 == todayJulianDay) {
	        			todayRelativeDesc = (String)getResources().getText(R.string.yesterday);
	        		} else if (julianDay-1 == todayJulianDay) {
	        			todayRelativeDesc = (String)getResources().getText(R.string.tomorrow);
	        		} else if (julianDay+2 == todayJulianDay) {
	        			todayRelativeDesc = (String)getResources().getText(R.string.before_yesterday);
	        		} else if (julianDay-2 == todayJulianDay) {
	        			todayRelativeDesc = (String)getResources().getText(R.string.after_tomorrow);
	        		} else if (julianDay < todayJulianDay) {
	        			todayRelativeDesc = String.format((String)getResources().getText(R.string.before_today), todayJulianDay - julianDay);
	        		} else {
	        			todayRelativeDesc = String.format((String)getResources().getText(R.string.after_today), julianDay - todayJulianDay);
	        		}
	        		((TextView)findViewById(R.id.daySummaryTitleLeftText)).setText(todayRelativeDesc);
	        		
	        		// Set full day desc text
	        		tempTime.setJulianDay(julianDay);
	        		Calendar date = Calendar.getInstance();
	        		date.set(Calendar.MONTH, tempTime.month);
	        		LunarCalendar lunar = new LunarCalendar();
	        		lunar.setSolarDate(julianDay);
	        		((TextView)findViewById(R.id.daySummaryTitleRightText)).setText(
	        			String.format(getResources().getString(R.string.day_long_desc), tempTime.year, DateFormat.format("MMMM", date), tempTime.monthDay, getResources().getStringArray(R.array.weekDayDesc)[tempTime.weekDay]) +
	        			"\n" + lunar.getFullDayDesc()
	        		);

	        		// Update the day summary list
	        		mDaySummaryAdapter.clear();
	        		for (Instance instance: instances) {
	        			if (instance.startDay <= julianDay && instance.endDay >= julianDay) {
	        				mDaySummaryAdapter.add(instance);
	        			}
	        		}
	        		mDaySummaryAdapter.notifyDataSetChanged();
	        		//mDaySummaryList.invalidate();
	        		
	        		// Display day summary view
	        		findViewById(R.id.daySummary).setVisibility(View.VISIBLE);
	        	}
	        });
        	monthListView.setMonthAsCurrent();
        	//listView.setAdapter(new ArrayAdapter<String>(this, R.layout.testview, COUNTRIES));
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); 
    	lp.setMargins(leftMargin, 1, rightMargin, 1);
        
        monthFrame.addView(monthListView, lp);

        //MonthView monthView = (MonthView)findViewById(R.id.MonthView);
        //monthView.setMonth(this, 2011, 4);
        
        // Calculate and set the height of day summary view
        findViewById(R.id.daySummary).getLayoutParams().height = (int)(display.getHeight() * 0.3);
    }
}